<?php
/**
 *      [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      http://www.haidao.la
 *      tel:400-600-2042
 */
class member_service extends service {
    protected $result;

    public function __construct() {
        $this->model = model('member/member');
        $this->setting = model('admin/setting', 'service')->get_setting();
        $this->group_model = model('member/member_group');
	}

    /**
     * 初始化
     * @return [type] [description]
     */
    public function init() {
        $_member = array(
            'id' => 0,
            'username' => '游客',
            'group_id' => 0,
            'email' => '',
            'mobile' => '',
            'money' => 0,
            'integral' => 0,
            'exp' => 0
        );
        $authkey = cookie('member_auth');
        if($authkey) {
	        list($mid, $password) = explode("\t", authcode($authkey));
	        $this->dologin($mid, $password);
	        $_member = $this->model->setid($mid)->address()->group()->output();
        }
        $_member['avatar'] = getavatar($_member['id']);
        // $_member['money'] = money($_member['money']);
        return $_member;
    }

    /**
     * 检测登录状态
     * @return 返回用户ID
     */
	public function check_login() {
        $authkey = cookie('member_auth');
        if($authkey) {
            list($mid, $password, $token) = explode("\t", $authkey);
            if(is_numeric($mid) && $password && $token) {
                if($this->model->fetch_by_id($mid, 'password') == $password) {
                    return $mid;
                }
            }
        }
        return FALSE;
	}

    /**
     * 注册
     * @param  array  $params 表单信息
     * @return mixed
     */
    public function register($params = array()) {
		if(empty($params)) {
			$this->error = '请勿非法提交';
			return false;
		}
        foreach( $params as $k => $v ) {
        	$method = '_valid_'.$k;
	        if(method_exists($this,$method) && $this->$method($v) === false) {
	            return false;
	        }        	
        }

        if($params['pwdconfirm'] != $params['password']) {
	        $this->error = '两次密码输入不一致';
	        return false;
        }
        
		$params['encrypt'] = random(6);
		$params['password'] = md5(md5($params['password']).$params['encrypt']);
		$params['group_id'] = 1;
		$params['islock'] = 0;
		$result = $this->model->update($params);
		if($result === false) {
			$this->error = $this->table->getError();
			return false;
		}
		$this->dologin($result, $params['password']);
        runhook('after_register');
        $this->login_inc($result);
		return $result;
    }

    public function login($account, $password) {
		if(empty($account)) {
			$this->error = '登录名不能为空';
			return false;
		}
		if(empty($password)) {
			$this->error = '登录密码不能为空';
			return false;
		}

		$sqlmap = array();
		if(is_mobile($account)) {
			$sqlmap['mobile'] = $account;
			$sqlmap['mobile_status'] = 1;
		} elseif(is_email($account)) {
			$sqlmap['email'] = $account;
			$sqlmap['email_status'] = 1;
		} else {
			$sqlmap['username'] = $account;
		}
		$member = $this->model->where($sqlmap)->find();
		if(!$member || md5(md5($password).$member['encrypt']) != $member['password']) {
			$this->error = '用户不存在或密码错误';
			return false;
		}
		if($member['islock'] == 1) {
			$this->error = '该用户已被锁定，禁止登录';
			return false;
		}
		$this->dologin($member['id'], $password);
        runhook('after_login', $member);
        $this->login_inc($member['id']);
		return true;
    }

    private function dologin($mid, $password) {
		$auth = authcode($mid."\t".$password, 'ENCODE');
		cookie('member_auth', $auth, 86400);
		$login_info = array(
			'id' => $mid,
			'login_time' => TIMESTAMP,
			'login_ip'	=> get_client_ip(),
		);
		$this->model->update($login_info);
        return true;
    }

    public function logout() {
	    return cookie('member_auth', null);
    }

    public function login_inc($mid){
        $this->model->where(array('id' => $mid))->setInc('login_num');
        return true;
    }

    /**
     * 变更经验值并判断自动升级
     * @param  int $mid 会员主键
     * @param  int $exp 变更的值
     * @return [bool]
     */
    public function action_exp($mid,$exp){
        $mid = (int) $mid;
        $exp = (int) $exp;
        $old_exp = (int) $this->model->fetch_by_id($mid,'exp');
        $info['id'] = $mid;
        $info['exp'] = (($old_exp + $exp) < 0) ? 0 : ($old_exp + $exp);
        $sqlmap['min_points'] = array("ELT", $info['exp']);
        $sqlmap['max_points'] = array("GT", $info['exp']);
        $group_id = $this->group_model->where($sqlmap)->getField('id');
        if($group_id < 1) return FALSE;
        $info['group_id'] = $group_id;
        $this->model->save($info);
        return TRUE;    
    }
    /**
     * 查询单个会员信息
     * @param int $id
     * @return mixed
     */
    public function fetch_by_id($id) {
        $r = $this->model->find($id);
        if(!$r) {
            $this->error = '_SELECT_NOT_EXIST_';
            return FALSE;
        }
        return $r;
    }

    /**
     * 删除指定会员
     * @param type $id
     */
    public function delete_by_id($id) {
        $ids = (array) $id;
        foreach($ids AS $id) {
            if($this->model->delete($id)) {
                /* 删除财务流水 */
                model('member_log')->where(array("mid" => $id))->delete();
                /* 删除收货地址 */
                model('member_address')->where(array("mid" => $id))->delete();
            }
        }
        return TRUE;
    }

    /**
     * 处理保证金
     * @param int $mid
     * @param string $money
     * @param isfrozen 操作类别（true:冻结；false:解冻）
     * @return boolean 状态
     */
    public function action_frozen($mid, $money, $isfrozen = true, $msg = '') {
        if($isfrozen === true) {
            $member_money = $this->model->where(array('id' => $mid))->getField('money');
            if(!$member_money || $member_money < $money) {
                $this->error = '用户余额不足';
                return false;
            }
            $_result = $this->model->where(array('id' => $mid))->setInc('frozen_money', $money);
            if(!$_result) {
                $this->error = $this->model->getError();
                return false;
            }
            $result = $this->model->where(array('id' => $mid))->setDec('money', $money);
            if(!$result) $this->model->where(array('id' => $mid))->setDec('frozen_money', $money);
            $log_money = '-'.$money;
        } else {
            $result = $this->model->where(array('id' => $mid))->setDec('frozen_money', $money);
            $log_money = $money;
        }
        if($result === false) {
            $this->error = $this->model->getError();
            return false;
        }
        $log_info = array(
            'mid'      => $mid,
            'value'    => $log_money,
            'type'     => 'money',
            'msg'      => $msg,
            'dateline' => TIMESTAMP,
            'admin_id' => (defined('IN_ADMIN')) ? ADMIN_ID : 0
        );
        model('member_log')->update($log_info);
        return true;
    }

    /**
     * 变更用户账户
     * @param int $mid
     * @param string $type
     * @param int $num
     * @param boolean $iswritelog
     * @return boolean 状态
     */
    public function change_account($mid, $field = 'money',$num, $msg = '',$iswritelog = TRUE) {
        $fields = array('money', 'exp', 'integral');
        if(!in_array($field, $fields)) {
            $this->error = '_PARAM_ERROR_';
            return FALSE;
        }
        $result = $this->model->where(array('id' => $mid))->setField($field, array("exp", $field.$num));
        if($result === FALSE) {
            $this->error = '_OPERATION_WRONG_';
            return FALSE;
        }
        if($iswritelog === TRUE) {
            $log_info = array(
                'mid'      => $mid,
                'value'    => $num,
                'type'     => $field,
                'msg'      => $msg,
                'dateline' => TIMESTAMP,
                'admin_id' => (defined('IN_ADMIN')) ? ADMIN_ID : 0
            );
            model('member_log')->update($log_info);
        }
        return TRUE;
    }
	 /**
     * 注册验证
     * @field string 验证字段
	 * @value string 值
     * @return boolean 返回值
     */
	public function valid($name,$value) {
        if(!$name || !$value){
            $this->error = "参数错误";
            return false;
        }
        $method = '_valid_'.$name;
        if(!method_exists($this,$method)) {
            $this->error = '参数错误';
            return false;
        }
        if($this->$method($value) === false) {
            return false;
        }
        return true;
	}

	/* 校验用户名 */
    private function _valid_username($value) {
        if(strlen($value) < 3 || strlen($value) > 15) {
            $this->error = '用户名长度在3-15个字符';
            return false;
        }
        $censorexp = '/^('.str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($this->setting['reg_user_censor'] = trim($this->setting['reg_user_censor'])), '/')).')$/i';
        if($this->setting['reg_user_censor'] && @preg_match($censorexp, $value)) {
            $this->error = '用户名含有被禁用的关键字';
            return false;
        }
        /* 检测重名 */
        if($this->model->where(array("username" => $value))->count()) {
            $this->error = '该用户名已被注册';
            return false;
        }
        return true;
    }

    /* 校验密码 */
    private function _valid_password($value) {
	    $reg_pass_lenght = max(3, (int) $this->setting['reg_pass_lenght']);
	    $reg_pass_complex = $this->setting['reg_pass_complex'];
	    if(strlen($value) < $reg_pass_lenght ) {
		    $this->error = '密码至少为 '. $reg_pass_lenght. ' 位字符';
		    return false;
	    }
	    if($reg_pass_complex) {
		    $strongpws = array();		    
			if(in_array('num',$reg_pass_complex) && !preg_match("/\d/",$value)){
				$strongpws[] = '数字';
			}
			if(in_array('small',$reg_pass_complex) && !preg_match("/[a-z]/",$value)){
				$strongpws[] = '小写字母';
			}
			if(in_array('big',$reg_pass_complex) && !preg_match("/[A-Z]/",$value)){
				$strongpws[] = '大写字母';
			}
			if(in_array('sym',$reg_pass_complex) && !preg_match("/[^a-zA-z0-9]+/",$value)){
				$strongpws[] = '特殊字符 ';
			}
			if($strongpws){
				$this->error = '密码必须包含'.implode(',', $strongpws);
				return false;
			}
	    }
	    return true;
    }

    private function _valid_email($value) {
	    if(!is_email($value)) {
		    $this->error = '邮箱格式不正确';
		    return false;
	    }

	    $_map = array();
	    $_map['email'] = $value;
	    $_map['emailstatus'] = 1;
        if($this->model->where($_map)->count()) {
            $this->error = '该邮箱已被注册';
            return false;
        }
        return true;
    }
    
    private function _valid_mobile($value) {
	    if(!is_mobile($value)) {
		    $this->error = '手机号码格式不正确';
		    return false;
	    }
	    $_map = array();
	    $_map['mobile'] = $value;
	    $_map['mobilestatus'] = 1;
        if($this->model->where($_map)->count()) {
            $this->error = '该手机号码已被注册';
            return false;
        }
        return true;
    }
    
}